<?php
class Database extends Object
{
	private $db_link;
	//private $obj_mysql;
	function __construct()
	{
		global $LinkID;
		$this->db_link = $LinkID;
	}
	/*
	 *parameter:  sql string, the name of the Class
	 *
	 *return:    successful:  			Array consists of the objects of this Class
	 Failed to connect DB:  null
	 No results:            0
	 returnType: 1 return object array, 0 return array
	 */
	function Query($sql,$returnType = 1)
	{
		if(defined('DATABASE_SQL_WATCHDOG') && DATABASE_SQL_WATCHDOG == true) {
			WatchDog::record($sql);
		}
		$result = mysqli_query($this->db_link, $sql);
		//die(var_dump($result));
		$num= @mysqli_num_rows($result);

		if($num!=0)
		{
			$i =0;
			$record = array();
			if($returnType)
			{
				while($row=mysqli_fetch_object($result))
				{
					$record[$i] = $row ;
					$i++;
				}
			}else{
				while($row=mysqli_fetch_array($result))
				{
					$record[$i] = $row ;
					$i++;
				}
			}

			return $record;
		} else {
			return array();
		}
	}

	public function QueryToArray($sql, $className)
	{
		$result = $this->Query($sql, $className);
		if( $result === 0){
			$result = array();
		}

		return $result;
	}

	/*
	 *parameter:  sql string, the name of the Class
	 *
	 *return:    The number which is the sql result;
	 */
	/***
	 * sql: select count(...) as NUM ...
	 * return: number
	 */
	function GetNum($sql)
	{
		return $this->GetFieldValue($sql);
	}

	function GetFieldValue($sql)
	{
		if(defined('DATABASE_SQL_WATCHDOG') && DATABASE_SQL_WATCHDOG == true) {
			WatchDog::record($sql);
		}
		
		$result = mysqli_query($this->db_link, $sql);
		
		if($result->num_rows != 0) {
			$row = mysqli_fetch_array($result);
		} else {
			return '';
		}
		return $row[0];
	}

	/*
	 *parameter:  sql string, the name of the Class
	 *
	 *return:    successful:  			The number of records
	 Failed to connect DB:  null
	 */
	function QueryNum($sql,$CLASS)
	{
		if(defined('DATABASE_SQL_WATCHDOG') && DATABASE_SQL_WATCHDOG == true) {
			WatchDog::record($sql);
		}
		
		$result = mysqli_query($this->db_link, $sql);
		$num= mysqli_num_rows($result);
		return $num;
	}

	/*
	 *parameter:  sql string, the name of the Class, handle of the return value
	 *
	 *return:    successful:  			when handle=1, return the id of the inserted record;  when 0, return 1
	 Failed to connect DB:  null
	 No results:            -1
	 */
	function add($sql, $handle=0)
	{
		if(defined('DATABASE_SQL_WATCHDOG') && DATABASE_SQL_WATCHDOG == true) {
			WatchDog::record($sql);
			
			if( defined('DATABASE_SQL_WATCHDOG_DIE') && DATABASE_SQL_WATCHDOG_DIE == true){
				die();
			}
		}
		
		if($result = mysqli_query($this->db_link, $sql))
		{
			$result =  mysqli_insert_id($this->db_link);
			if($handle == 1){
				return $result;
			} else {
				return true;
			}
		} else {
			return false;
		}
	}
	
	/*
	 *parameter:  sql string, the name of the Class
	 *
	 *return:    successful:  			1
	 Failed to connect DB:  null
	 No results:            -1
	 */
	function edit($sql)
	{
		if(defined('DATABASE_SQL_WATCHDOG') && DATABASE_SQL_WATCHDOG == true) {
			WatchDog::record($sql);
			
			if( defined('DATABASE_SQL_WATCHDOG_DIE') && DATABASE_SQL_WATCHDOG_DIE == true){
				die();
			}
		}
		
		if(!$result = mysqli_query($this->db_link, $sql)) {
			return false;
		} else {
			if( $this->db_link->affected_rows == 0 ){
				return false;
			} else {
				return true;
			}
			
			return  true;
		}
	}

	/*
	 *parameter:  sql string, the name of the Class
	 *
	 *return:    successful:  			1
	 Failed to connect DB:  null
	 No results:            -1
	 */
	function delete($sql)
	{
		if(defined('DATABASE_SQL_WATCHDOG') && DATABASE_SQL_WATCHDOG == true) {
			WatchDog::record($sql);
			
			if( defined('DATABASE_SQL_WATCHDOG_DIE') && DATABASE_SQL_WATCHDOG_DIE == true){
				die();
			}
		}
		
		if(!$result = mysqli_query($this->db_link, $sql)) {
			
			return false;
		} else {
			if( $this->db_link->affected_rows == 0 ){
				return false;
			} else {
				return true;
			}
			
			return  true;
		}
	}
	
	function getTranResult($array_sql)
	{
		mysqli_autocommit($this->db_link, FALSE);
		$record = array();
		$error = false;
		foreach($array_sql as $item)
		{
			if(!$item['return'])
			{
				if(defined('DATABASE_SQL_WATCHDOG') && DATABASE_SQL_WATCHDOG == true) {
					WatchDog::record($item['sql']);
				}
				$this->db_link->query($item['sql']);
				$record[] = "";
				if(mysqli_error($this->db_link))
				{
					$error = true;
					break;
				}
				continue;
			}
			$result = $this->db_link->query($item['sql']);
			if(mysqli_error($this->db_link))
			{
					$error = true;
					break;
			}
			if($result)
			{
		    //$this->db_link->commit();
		    $num= @mysqli_num_rows($result);

				if($num!=0)
				{
					$i =0;
					$rows = array();

					while($row=mysqli_fetch_object($result))
					{
						$rows[$i] = $row ;
						$i++;
					}

					$record[] = $rows;
		    }else{
		    	$record[] = "";
		    }
			}
		}
		if($error)
		{
			$this->db_link->rollback();
		}else{
			$this->db_link->commit();
		}

		mysqli_autocommit($this->db_link, true);

		return $record;
	}



	function beforeAddTransCheck($array_sql, $handle=0)
	{
		mysqli_autocommit($this->db_link, FALSE);
		foreach($array_sql as $item)
		{
			$result = mysqli_query($this->db_link,$item['sql']);
			//print_r($result);
			//echo "<br>";
				if(mysqli_error($this->db_link))
				{
					//echo "sql: ". $item['sql'];
					//exit;
					$this->db_link->rollback();
					mysqli_autocommit($this->db_link, true);
					return false;
				}

				if($item['return'])
				{
					if( mysqli_num_rows($result)<0)
					{
						//echo "return1 <br>";
						$this->db_link->rollback();
						mysqli_autocommit($this->db_link, true);
						//echo $item['sql'];
						//exit;
						return false;
					}
				}else{
					if(mysqli_num_rows($result)>0)
					{
						//print_r($result);
						//echo "count: ".count($result)." <br>";
						$this->db_link->rollback();
						mysqli_autocommit($this->db_link, true);
						// echo $item['sql'];
						//exit;
						return false;
					}
				}
		}

		return true;
	}

	function Transaction($array_sql, $handle=0)
	{
		$ids = array();
		$ids_new = array();
		$is_new_usage = false;

		mysqli_autocommit($this->db_link, false);
		$sql_count = count($array_sql);
		$id_count = 0;

		for($i=0; $i<$sql_count; $i++)
		{
			if(is_array($array_sql[$i])){
				$sql = $array_sql[$i]["sql"];
				$is_new_usage = true;
			} else {
				$sql = $array_sql[$i];
			}
			
			if(defined('DATABASE_SQL_WATCHDOG') && DATABASE_SQL_WATCHDOG == true) {
				WatchDog::record($sql);
			}
			
			$id_count = count($ids);
			for($h=0; $h<$id_count; $h++){
				$sql = str_replace("ITEM[".$h."]", $ids[$h], $sql);
			}

			$this->db_link->query($sql);

			if(mysqli_error($this->db_link)) {
				if( ISLOCAL ) {
					echo '<span style="color: red;">sql error:</span> '.$sql."<br />";
					echo mysqli_error($this->db_link);
					
					exit;
				}
				
				$this->db_link->rollback();
				mysqli_autocommit($this->db_link, true);

				return false;
			}

			$ids[$i] = mysqli_insert_id($this->db_link);

			if(is_array($array_sql[$i]) && $array_sql[$i]["return"]==true){
				$ids_new[$i] = $ids[$i];
			}
		}

		$this->db_link->commit();
		mysqli_autocommit($this->db_link, true);

		if($handle==0){
			return true;
		} else if($handle==1){
			return $ids[0];
		} else if($handle==3){
			if($is_new_usage==true){
				return $ids_new;
			} else {
				return $ids;
			}
		}
	}
	
	/*
	 *parameter:  SQLs Array, like arr[0],arr[1],arr[2].
	 *
	 *return:    successful:  			1
	 Failed to connect DB:  null
	 No results:            -1
	 */
	function TransactionTemporary($array_sql, $temp_table)
	{
		$all_query_ok = true; // our control variable
		mysqli_autocommit($this->db_link, FALSE);
		//die(var_dump(count($array_sql)));
		for($i=0; $i<count($array_sql); $i++){
			if( $i < count($array_sql)-1 ){
				//echo($array_sql[$i]);
				$this->db_link->Query($array_sql[$i]) ? null : $all_query_ok=false;
				if($all_query_ok==false){
					//die($array_sql[$i]);
					break;
				}
			} else {
				$result = $this->query($array_sql[$i]);
			}
		}

		$this->db_link->query("drop table ".$temp_table);

		$all_query_ok ? $this->db_link->commit() : $this->db_link->rollback();
		mysqli_autocommit($this->db_link, true);
		return $result;
	}
	
	function injection_strict($data)
	{
		if( is_array($data) ) {
			foreach($data as $key=>$value) {
				$data[$key] = $this->injection_strict($value);
			}
		} elseif(is_object($data)){
			$vars = get_object_vars($data);
			
			foreach($vars as $key=>$value) {
				$data->$key = $this->injection_strict($value);
			}
		} elseif( is_string($data)) {
			return mysqli_real_escape_string($this->db_link, $data);
		} else {
			return $data;
		}
		
		return $data;
	}
	
	function sql_set_default_value($value, $default)
	{
		if( isset($value) && !empty($value))
		{
			return $value;
		}
		
		return $default;
	}
	
	function sql_append_add($field_name, $field_value, $return_exist=array())
	{
		$array_add = array();
		
		if($field_value != '') {
			$array_add['fields'] = ", {$field_name}";
			$array_add['values'] = ", '{$field_value}'";
			if( !empty($return_exist) ) {
				$array_add['fields'] = $return_exist['fields'].$array_add['fields'];
				$array_add['values'] = $return_exist['values'].$array_add['values'];
			}
		}
		
		return $array_add;
	}
	
	function sql_append_update($field_name, $field_value)
	{
		if($field_value != '') {
			return ", {$field_name}= '{$field_value}'";
		}
		return '';
	}
	
	function sql_append_condition($field_name, $field_value)
	{
		if($field_value != '') {
			return " and {$field_name}= '{$field_value}'";
		}
		return '';
	}
}
?>